package com.shenghuozhushou;

import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.shenghuozhushou.fragments.ConcentrationFragment;
import com.shenghuozhushou.fragments.MusicFragment;
import com.shenghuozhushou.fragments.TaskFragment;
import com.shenghuozhushou.fragments.WeatherFragment;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private List<Fragment> fragmentList = new ArrayList<>();
    private FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 初始化底部导航栏：
        initBottomNavigation();
    }

    // 初始化底部导航栏：
    public void initBottomNavigation() {
        // 添加要纳入管理的 fragment 实例到 fragmentList ：
        fragmentList.add(new TaskFragment());
        fragmentList.add(new ConcentrationFragment());
        fragmentList.add(new MusicFragment());
        fragmentList.add(new WeatherFragment());

        // 建立 fragment 管理器：
        fragmentManager = getSupportFragmentManager();

        // 管理器开启事务，并将 fragment 实例加入到管理器当中：
        fragmentManager.beginTransaction()
                .add(R.id.fragment_holder, fragmentList.get(0), "TASK")
                .add(R.id.fragment_holder, fragmentList.get(1), "CONCENTRATION")
                .add(R.id.fragment_holder, fragmentList.get(2), "MUSIC")
                .add(R.id.fragment_holder, fragmentList.get(3), "WEATHER")
                .commit();

        // 设置 fragment 初始显示状态，为 Task 界面：
        showFragment(0);

        // 设置底部导航栏的 click 事件监听器，切换到对应的 fragment ：
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            if (item.getItemId() == R.id.menu_task) { showFragment(0); return true; }
            else if (item.getItemId() == R.id.menu_concentration) { showFragment(1); return true; }
            else if (item.getItemId() == R.id.menu_music) { showFragment(2); return true; }
            else if (item.getItemId() == R.id.menu_weather) { showFragment(3); return true; }
            else { Log.i(MainActivity.class.getName(), "onNavigationItemSelected: Error"); }
            return false;
        });
    }

    private void showFragment(int index) {
        // 在 show 对应的 fragment 时隐藏其余的 fragment ：
        fragmentManager.beginTransaction()
                .show(fragmentList.get(index))
                .hide(fragmentList.get((index + 1) % 4))
                .hide(fragmentList.get((index + 2) % 4))
                .hide(fragmentList.get((index + 3) % 4))
                .commit();
    }
}